//
// Created by denglibin on 19-10-23.
//

/**
 *读写锁: 读共享，写独占 （只有一把锁，有读模式和写模式），竞争锁时写优先级高于读优先级
 **/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>

static pthread_rwlock_t rw_lock; // 读写锁

static int i = 0; // 全局资源

/**
 * 写操作
 * @param arg
 * @return
 */
static void * t_fun_write(void * arg){
    pthread_rwlock_wrlock(&rw_lock);// 加写锁 只能有一个线程获得
    int x = 20;
    while (x--){
        i++;
        printf("write: t_id =%lu ,i = %d\n", pthread_self(), i);
    }
    pthread_rwlock_unlock(&rw_lock); // 解锁
    return NULL;
}
/**
 * 读操作
 * @param arg
 * @return
 */
static void * t_fun_read(void * arg){
    pthread_rwlock_rdlock(&rw_lock);// 加读锁 多个线程可同时获得锁
    int x  = 20;
    while(x--){
        usleep(100 * 1000);
        printf("read: t_id =%lu ,i = %d\n", pthread_self(), i);
    }

    pthread_rwlock_unlock(&rw_lock); // 解锁
    return NULL;
}

static int main_(){
    pthread_rwlock_init(&rw_lock, NULL);
    pthread_t t1, t2, t3, t4;
    pthread_create(&t1, NULL, t_fun_write, NULL);
    pthread_create(&t2, NULL, t_fun_write, NULL);
    sleep(1);
    pthread_create(&t3, NULL, t_fun_read, NULL);
    pthread_create(&t4, NULL, t_fun_read, NULL);

    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    pthread_join(t3, NULL);
    pthread_rwlock_destroy(&rw_lock);
    return 0;
}


